package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Department;
import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.mapper.EmployeeMapper;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IEmployeeService;
import cn.wolfcode.wms.utils.LogicException;
import cn.wolfcode.wms.utils.MD5;
import cn.wolfcode.wms.utils.PageResult;
import cn.wolfcode.wms.utils.UserContext;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper mapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {

        mapper.deleteByPrimaryKey(id);
        mapper.deleteEmployeeRoleRelation(id);
    }

    @Override
    public void insert(Employee entity,Long[] roleIds) {
        entity.setPassword(MD5.encode(entity.getPassword()));
        mapper.insert(entity);
        //2.在保存员工之后,我们需要保存该员工和角色之间的关系
        if (roleIds!=null){

            for (Long roleId : roleIds) {

                mapper.saveEmployeeRoleRelations(entity.getId(),roleId);
            }
        }
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {

        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public void updateByPrimaryKey(Employee entity,Long[] roleIds) {

        mapper.updateByPrimaryKey(entity);
        //2.在更新员工和角色之间的关系,此时我们需要先删除之前的旧关系
        mapper.deleteEmployeeRoleRelation(entity.getId());
        //3.保存两者之间的新关系
        if (roleIds!=null){
            for (Long roleId : roleIds) {
                mapper.saveEmployeeRoleRelations(entity.getId(),roleId);
            }
        }
    }

    @Override
    public PageResult query(QueryObject qo) {

        Long totalCount = mapper.queryForCount(qo);
        if (totalCount == 0){
            return new PageResult(qo.getPageSize());
        }
        List<Employee> listData = mapper.queryForList(qo);
        return new PageResult(listData,totalCount,qo.getCurrentPage(),qo.getPageSize());
    }
    //批量删除
    @Override
    public void batchDelete(Long[] ids) {
        mapper.batchDelete(ids);
    }
    @Override
    public void login(String name, String password) {

        Employee curent = mapper.login(name,MD5.encode(password));
        if (curent==null){

            throw new LogicException("账号和密码不匹配");
        }
        //1.将当前对象共享到session中
       UserContext.setEmployee(curent);
        //2.查询该用户当前所有的权限表达式,共享到session作用域中
        List<String> expressions = permissionMapper.selectPermissionsByEmployeeId(curent.getId());
        UserContext.setExpression(expressions);

    }


}
